
#import "SMBannerView.h"
#import "../../Models/SMBanner.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface SMBannerView () <UIScrollViewDelegate>
@property(nonatomic, strong) UIScrollView *scroll;
@property(nonatomic, strong) UIPageControl *page;
@property(nonatomic, strong) NSTimer *timer;
@end

@implementation SMBannerView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _scroll = [UIScrollView new];
        _scroll.pagingEnabled = YES;
        _scroll.showsHorizontalScrollIndicator = NO;
        _scroll.delegate = self;
        _page = [UIPageControl new];
        [self addSubview:_scroll];
        [self addSubview:_page];
        [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [_page mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-10);
            make.bottom.equalTo(self).offset(-6);
        }];
    }
    return self;
}
- (void)setBanners:(NSArray<SMBanner *> *)banners {
    _banners = banners;
    for (UIView *v in _scroll.subviews) [v removeFromSuperview];
    CGFloat w = self.bounds.size.width, h = self.bounds.size.height;
    _scroll.contentSize = CGSizeMake(w * banners.count, h);
    _page.numberOfPages = banners.count;
    for (NSInteger i=0;i<banners.count;i++){
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(w*i, 0, w, h)];
        iv.contentMode = UIViewContentModeScaleAspectFill;
        iv.clipsToBounds = YES;
        [iv sd_setImageWithURL:[NSURL URLWithString:banners[i].imageURL]];
        iv.userInteractionEnabled = YES;
        iv.tag = i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBanner:)];
        [iv addGestureRecognizer:tap];
        [_scroll addSubview:iv];
    }
    [self startTimer];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    // re-layout on rotation
    [self setBanners:self.banners];
}
- (void)startTimer {
    [_timer invalidate];
    if (self.banners.count <= 1) return;
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(tick) userInfo:nil repeats:YES];
}
- (void)tick {
    NSInteger page = (_page.currentPage + 1) % MAX(self.banners.count, 1);
    CGFloat w = self.bounds.size.width;
    [_scroll setContentOffset:CGPointMake(w*page, 0) animated:YES];
    _page.currentPage = page;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat w = self.bounds.size.width;
    if (w > 0) _page.currentPage = round(scrollView.contentOffset.x / w);
}
- (void)tapBanner:(UITapGestureRecognizer *)gr {
    NSInteger idx = gr.view.tag;
    if (idx < self.banners.count && self.onTap) self.onTap(self.banners[idx]);
}
@end
